// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System.Data;
using System.Data.Common;
using JetBrains.Annotations;
using Npgsql;

namespace SnapObjects.Data.PostgreSql
{
    public class PostgreSqlDateTimeOffsetTypeMapping : DateTimeOffsetTypeMapping
    {
        private const string DateTimeOffsetFormatConst = "{0:yyyy-MM-ddTHH:mm:ss.FFFFFFzzz}";

        /// <summary>
        ///     Initializes a new instance of the <see cref="PostgreSqlDateTimeOffsetTypeMapping" /> class.
        /// </summary>
        /// <param name="dbTypeName"> The name of the database type. </param>
        /// <param name="dbType"> The <see cref="System.Data.DbType" /> to be used. </param>
        public PostgreSqlDateTimeOffsetTypeMapping(
            [NotNull] string dbTypeName,
            [NotNull] DbType? dbType = System.Data.DbType.DateTimeOffset)
            : base(dbTypeName, dbType: dbType)
        {
        }

        /// <summary>
        ///     Creates a copy of this mapping.
        /// </summary>
        /// <param name="dbTypeName"> The name of the database type. </param>
        /// <param name="size"> The size of data the property is configured to store, or null if no size is configured. </param>
        /// <returns> The newly created mapping. </returns>
        public override TypeMapping Clone(string dbTypeName, int? size)
        {
            return new PostgreSqlDateTimeOffsetTypeMapping(dbTypeName, this.DbType);
        }

        protected override void ConfigureParameter([NotNull] DbParameter parameter, IAdoDbParameter adoDbParameter)
        {
            base.ConfigureParameter(parameter, adoDbParameter);

            if (parameter is NpgsqlParameter p)
            {
                p.NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.TimestampTz;
            }
        }

        /// <summary>
        ///     Gets the string format to be used to generate SQL literals of this type.
        /// </summary>
        protected override string SqlLiteralFormatString => "'" + DateTimeOffsetFormatConst + "'";
    }
}
